<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="card-title">系统登录</h2>
      </template>
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="rules"
          label-width="80px"
          @keyup.enter="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :disabled="loading"
              clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :disabled="loading"
              clearable
              show-password
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" class="forget-password" @click="handleForgetPassword">
            忘记密码？
          </el-link>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              :loading="loading"
              @click="handleLogin"
              class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
          <el-button
              @click="$router.push('/register')"
              :disabled="loading"
          >
            注册账号
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const loginFormRef = ref(null)
const rememberMe = ref(false)

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

// 在组件挂载时检查本地存储的登录信息
onMounted(() => {
  const savedUsername = localStorage.getItem('username')
  if (savedUsername) {
    loginForm.username = savedUsername
    rememberMe.value = true
  }
})

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true
    await userStore.login(loginForm)

    // 处理"记住我"功能
    if (rememberMe.value) {
      localStorage.setItem('username', loginForm.username)
    } else {
      localStorage.removeItem('username')
    }

    ElMessage.success('登录成功')
    await router.push('/')
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}

// 处理忘记密码
const handleForgetPassword = () => {
  ElMessage.info('请联系管理员重置密码')
  // 这里可以添加跳转到重置密码页面的逻辑
  // router.push('/reset-password')
}

// 重置表单
const resetForm = () => {
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-title {
  text-align: center;
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.login-button {
  width: 100%;
  margin-bottom: 10px;
}

.forget-password {
  float: right;
  font-size: 14px;
}

:deep(.el-form-item__content) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-button) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style>